package com.cntaiping.royal.bass.common.util;

import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * 七牛云存储的视频文件上传 和视频转码工具等
 */
public class QiNiuPutFile {

    private static Logger log = LoggerFactory.getLogger(QiNiuPutFile.class);


    public static String upload(File file, String fileType) throws IOException {

        // 构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());

        //其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        String qiniuShowUrl="https://qiniu.weshoes.com.cn/";

        String qiniuUpUrl="http://upload.qiniup.com/putb64/";

        //生成上传凭证，然后准备上传
        String accessKey = "QQrqlX3GS45sKJVvroB5G75rcj0C3vuKqph34oYC";

        String secretKey = "6E2H2fhe8NeIjncVYONjesQaKZFK-Ityu5JER12V";

        //上传到指定的七牛云存储的一个空间中
        String bucket = "weshoes";


        //得到上传文件的文件名，并赋值给key作为七牛存储的文件名
        String key = DateUtil.dateToString(new Date(), "yyyyMMddHHmmss") + "." + fileType;

        //进行七牛的操作，不懂去七牛的sdk上看
        Auth auth = Auth.create(accessKey, secretKey);

        //设置转码操作参数
        String fops = "avthumb/mp4/vcodec/libx264";

        //可以对转码后的文件进行使用saveas参数自定义命名，当然也可以不指定文件会默认命名并保存在当前空间。
        String urlbase64 = UrlSafeBase64.encodeToString(bucket + ":" + key);
        String pfops = fops + "|saveas/" + urlbase64;
        String upToken = auth.uploadToken(bucket, null, 3600, new StringMap().putNotEmpty("persistentPipeline", pfops));


        //返回值
        String retuenValue = null;

        try {
            //进行上传操作，传入文件的字节数组，文件名，上传空间，得到回复对象
            Response response = uploadManager.put(file.getPath(), key, upToken);

            if(response!=null && response.statusCode == 200){
                retuenValue = qiniuShowUrl + key;
            }
        }catch (Exception e){
            e.getMessage();
            log.info("上传失败");
        }


        return retuenValue;
    }
}